<?php
declare(strict_types = 1);

namespace app\controller;

use app\ArrayToolkit;
use app\BaseController;
use app\logic\SendMessageLog;
use think\Request;

class SendLog extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $fields =  $fields = $request->param(false);

        list($conditions, $page, $limit) = $this->buildConditions($fields);

        $total = $this->getSendLogLogic()->countSendMessageLog($conditions);
        $sendLogic = $this->getSendLogLogic()->searchSendMessageLogs(
            $conditions,
            ['id', 'DESC'],
            $page,
            $limit
        );

        $userIds = ArrayToolkit::column($sendLogic, 'user_id');
        $templateIds = ArrayToolkit::column($sendLogic, 'template_id');

        $users = ArrayToolkit::index($this->getUserLogic()->findUserByIds($userIds), 'id');
        $templates = ArrayToolkit::index($this->getTemplateLogic()->findTemplateByIds($templateIds), 'id');
        return $this->createJsonResponse([
            'total' => $total,
            'sendLogic' => $sendLogic,
            'users' => $users,
            'templates' => $templates,
        ]);
    }

    protected function buildConditions($fields)
    {
        $page = 0;
        $limit = 20;
        $conditions = [];

        return [$conditions, $page, $limit];
    }

    /**
     * @return SendMessageLog
     */
    protected function getSendLogLogic(): \app\logic\SendMessageLog
    {
        return $this->getLogic('SendMessageLog');
    }

    /**
     * @return \app\logic\User
     */
    protected function getUserLogic(): \app\logic\User
    {
        return $this->getLogic('User');
    }

    /**
     * @return \app\logic\Template
     */
    protected function getTemplateLogic(): \app\logic\Template
    {
        return $this->getLogic('Template');
    }
}
